package learningThread.syn.synchronizedMethodLockObj.lock.readwritelock.readAndWrite;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读锁:共享锁,多个读锁相互之间不排斥,
 */
public class Service {

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void read(){
        try {
            lock.readLock().lock();
            System.out.println("获取到线程读锁:"+Thread.currentThread().getName() +",开始于:"+System.currentTimeMillis());
            Thread.sleep(5000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
            System.out.println("释放线程读锁:"+Thread.currentThread().getName() +",结束于:"+System.currentTimeMillis());
        }
    }

    public void write() {
        try {
            lock.writeLock().lock();
            System.out.println("获取到线程写锁:"+Thread.currentThread().getName() +",开始于:"+System.currentTimeMillis());
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
            System.out.println("释放线程写锁:"+Thread.currentThread().getName() +",结束于:"+System.currentTimeMillis());
        }
    }
}
